<script setup>
import { ref } from "vue";
import axios from "axios";

const props = defineProps({
  // 抽屉标题
  title: {
    type: String,
    default: "AI助手",
  },
  // 设置抽屉宽
  width: {
    type: String,
    default: "30%",
  }
})

const drawer = ref(false); // 控制抽屉显隐

const apiKey = import.meta.env.VITE_DEEPSEEK_API_KEY
const baseURL = import.meta.env.VITE_DEEPSEEK_BASE_URL
const messages = ref([{ role: 'system', content: '你好，我是你的智能助手' }])
const userInput = ref('')
const isLoading = ref(false)
const sendToDeepSeek = async () => {
  try {
    isLoading.value = true
    const response = await axios.post(
        `${baseURL}/chat/completions`,
        {
          model: 'deepseek-chat',
          messages: [...messages.value, { role: 'user', content: userInput.value }],
          temperature: 0.7,
          stream: false // 流式传输需特殊处理
        },
        {
          headers: {
            'Authorization': `Bearer ${apiKey}`,
            'Content-Type': 'application/json'
          }
        }
    )
    userInput.value = ""
    messages.value.push(response.data.choices[0].message)
    //打字机效果
    //typewriterEffect(response.data.choices[0].message.content, document.querySelector('.ql-editor'))
  } catch (error) {
    console.error('API调用失败:', error.response?.data || error.message)
  } finally {
    isLoading.value = false
  }
};
function typewriterEffect(text, targetElement) {
  let index = 0
  const timer = setInterval(() => {
    targetElement.innerHTML += text[index++]
    if (index >= text.length) clearInterval(timer)
  }, 50)
}

// 打开抽屉
function open() {
  drawer.value = true;
}
// 关闭抽屉
const resetForm = () => {
  drawer.value = false;
};
defineExpose({
  open,
});
</script>
<template>
  <el-drawer
      v-model="drawer"
     :title="title"
     :size="width"
     :before-close="resetForm">
    <div class="ql-container ql-snow chat-container">
      <div class="ql-editor" v-for="(msg, index) in messages" :key="index">
        <div id="messagedetail" :class="['message', msg.role]">
          {{ msg.content }}
        </div>
      </div>
    </div>
    <el-input v-model="userInput" style="width: 17vw" size="large" readonly="isLoading" @keyup.enter="sendToDeepSeek"/>
    <el-button :disabled="isLoading" size="large" style="margin-left: 5px;width: 6vw" @click="sendToDeepSeek" type="primary">
      {{ isLoading ? '生成中...' : '发送' }}
    </el-button>
  </el-drawer>
</template>
<style scoped>
.chat-container {
  max-width: 800px;
  max-height: 85vh;
  height: auto;
  overflow-y: scroll;
}
.ql-editor{
  max-height: 85vh;
}
#messagedetail{
  color: #2c3e50;
  padding: 12px;
  background: #caffbc;
  border-radius: 8px;
}
</style>









